package com.study.exception;

import cn.dev33.satoken.exception.DisableLoginException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import com.study.util.result.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalException {

    @ExceptionHandler
    public ApiResult handlerException(Exception exception) {
        exception.printStackTrace();
        log.error("全局异常：{}", exception.getMessage());
        if (exception instanceof NotLoginException) {
            return ApiResult.FALL(exception.getMessage());
        } else if (exception instanceof NotRoleException) {
            NotRoleException e = (NotRoleException) exception;
            return ApiResult.FALL("无此角色：" + e.getRole());
        } else if (exception instanceof NotPermissionException) {
            NotPermissionException e = (NotPermissionException) exception;
            return ApiResult.FALL("权限不足" + e.getCode());
        } else if (exception instanceof DisableLoginException) {
            return ApiResult.FALL("账号被封禁");
        } else if (exception instanceof ServiceException) {
            return ApiResult.FALL(exception.getMessage());
        } else {
            return ApiResult.FALL("服务器异常");
        }
    }

    @ExceptionHandler(NotLoginException.class)
    public ApiResult handlerNotLoginException(NotLoginException notLoginException) {
        notLoginException.printStackTrace();
        String message = "";
        if (notLoginException.getType().equals(NotLoginException.NOT_TOKEN)) {
            message = "token not found";
        } else if (notLoginException.getType().equals(NotLoginException.INVALID_TOKEN)) {
            message = "token无效";
        } else if (notLoginException.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            message = "token已过期";
        } else if (notLoginException.getType().equals(NotLoginException.BE_REPLACED)) {
            message = "token被顶下线";
        } else if (notLoginException.getType().equals(NotLoginException.KICK_OUT)) {
            message = "token被踢下线";
        } else {
            message = "当前会话未登录";
        }
        return ApiResult.FALL(message);
    }
}
